package com.gx.smart.building.ui.inspection.fragment

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.TimeUtils
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.gx.smart.base.BaseMVVMFragmentV2
import com.gx.smart.building.R
import com.gx.smart.building.databinding.FragmentInspectionDetailBinding
import com.gx.smart.building.ui.inspection.InspectionTransformActivity
import com.gx.smart.building.ui.inspection.adapter.TaskPageAdapter
import com.gx.smart.building.ui.inspection.event.FinishedQuantityEvent
import com.gx.smart.building.ui.inspection.event.TaskInCompleteEvent
import com.gx.smart.building.ui.inspection.event.UnfinishedQuantityEvent
import com.gx.smart.building.ui.inspection.viewmodel.InspectionViewModel
import com.gx.smart.lib.http.api.response.PlanTask
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.dto.PlanTaskDto
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class InspectionDetailFragment : BaseMVVMFragmentV2<InspectionViewModel>(),
    View.OnClickListener,
    TextView.OnEditorActionListener {
    private lateinit var viewBinding: FragmentInspectionDetailBinding
    private lateinit var mPagerAdapter: TaskPageAdapter
    private var item: PlanTask? = null
    override fun getToolbarTitle(): String = "任务列表"

    override fun onBindLayout(): Int = R.layout.fragment_inspection_detail

    override fun onBindViewModel(): Class<InspectionViewModel> = InspectionViewModel::class.java

    override fun initContentView(root: ViewGroup) {
        viewBinding = FragmentInspectionDetailBinding.inflate(layoutInflater, root, true)
        viewBinding.search.setOnEditorActionListener(this)
        viewBinding.clear.setOnClickListener(this)
        viewBinding.transform.setOnClickListener(this)
        viewBinding.save.setOnClickListener(this)
    }

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            search()
            KeyboardUtils.hideSoftInput(v!!)
            return true
        }
        return false
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.clear -> viewBinding.search.editableText.clear()
            R.id.transform -> transform()
            R.id.save -> forward()
        }
    }

    private fun forward() {
        val intent = Intent(requireActivity(), InspectionTransformActivity::class.java)
        intent.putExtra("id", item?.id)
        startActivity(intent)
    }

    private fun transform() {
        viewBinding.submitLayout.visibility = View.VISIBLE
    }


    private fun search() {
        val name = viewBinding.search.text.toString().trim()
        (mPagerAdapter.getItem(viewBinding.viewPager.currentItem) as CommonFragment).search(name)
    }


    override fun initData() {
        requireActivity().intent.getStringExtra("id")?.let { id ->
            val titles = resources.getStringArray(R.array.task)
            mPagerAdapter = TaskPageAdapter(requireActivity())
            val fragmentList = mPagerAdapter.getList()
            fragmentList[0].arguments = Bundle().apply {
                putString("id", id)
            }
            fragmentList[1].arguments = Bundle().apply {
                putString("id", id)
            }
            viewBinding.viewPager.adapter = mPagerAdapter
            viewBinding.viewPager.isUserInputEnabled = true

            TabLayoutMediator(
                viewBinding.tabLayout, viewBinding.viewPager
            ) { tab: TabLayout.Tab, position: Int ->
                tab.text = titles[position] + "(10)"
            }.attach()

//            if (list[0] < 1) {
                viewBinding.status.text = "已完成"
                viewBinding.cardLayout.background =
                    resources.getDrawable(R.mipmap.ic_complete_task)
                viewBinding.transform.visibility = View.GONE
//            }
        }



        requireActivity().intent.getIntExtra("position", 0).let {
            viewBinding.viewPager.currentItem = it
        }
        arguments?.getInt("position")?.let {
            viewBinding.viewPager.currentItem = it
        }
        registerEventBus()
        item?.let {
            viewBinding.planName.text = it.planName
            viewBinding.taskCode.text = "任务编号：${it.taskCode}"
            val validTime = TimeUtils.millis2String(it.validTime, "yyyy-MM-dd HH:mm")
            val invalidTime = TimeUtils.millis2String(it.invalidTime, "yyyy-MM-dd HH:mm")
            viewBinding.time.text =
                "执行时间：$validTime-$invalidTime" //执行时间：2022-05-01 12:00 — 2022-05-10 12:00
            viewBinding.deviceTotal.text = "巡检设备数量: ${it.deviceTotal}"
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun handleEvent(event: TaskInCompleteEvent) {
        item = event.item
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun handleEventOne(event: FinishedQuantityEvent) {
        viewBinding.tabLayout.getTabAt(1)?.text = "已完成(${event.finishQuantity})"
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun handleEventTwo(event: UnfinishedQuantityEvent) {
        viewBinding.tabLayout.getTabAt(0)?.text = "未完成(${event.unfinishedQuantity})"
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterEventBus()
    }
}